<template>
	<view class="gui-relative" style="height:100vh;">
		<view>
			<view class="gui-box-shadow-md gui-border-box gui-relative">
				<view class="" style="min-height:700rpx;background: linear-gradient(180deg,#17ead9,#6078ea);">
					<view class="gui-color-white gui-relative" style="right:60rpx;bottom:60rpx;">
						<view class="gui-padding" style="text-align: center;">
							<rich-text :nodes="groupactivity.introduce"></rich-text>
						</view>
					</view>
				</view>

			</view>
			<view class="hulu-empty-paragraph"></view>
			<view class="gui-padding gui-relative" style="background: linear-gradient(135deg,#ffd26f,#3677ff);">
				<view class="gui-flex gui-justify-content-start gui-align-items-center">
					<u-icon name="tags-fill" color="#2979ff" size="32"></u-icon>
					<text class="gui-h6 gui-boldder" style="color:#2979ff;">当前抢购</text>
				</view>
				<view class="gui-flex gui-space-between gui-align-items-center ">
					<view class="">
						<gui-tags :text="`(${groupactivity.current_number}/${groupactivity.require_number})`"
							:borderRadius="50"></gui-tags>
					</view>

				</view>
				<view class="gui-absolute-rt" style="width: 100%;height:100%; ">
					<view class="gui-absolute-rt" style="top:30rpx;right:30rpx;">
						<up-count-down ref="countDownRef" v-if="toStartTime>0" :time="toStartTime" format="DD:HH:mm:ss"
							autoStart millisecond @change="onChange">
							<view class="time">
								<text class="time__item">距离开始</text>
								<text class="time__item">{{ timeData.days }}&nbsp;天</text>
								<text
									class="time__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}&nbsp;时</text>
								<text class="time__item">{{ timeData.minutes }}&nbsp;分</text>
								<text class="time__item">{{ timeData.seconds }}&nbsp;秒</text>
							</view>
						</up-count-down>

						<up-count-down ref="countDownRef" v-if="toStartTime<0" :time="remainTime" format="DD:HH:mm:ss"
							autoStart millisecond @change="onChange">
							<view class="time">
								<text class="time__item">剩余</text>
								<text class="time__item">{{ timeData.days }}&nbsp;天</text>
								<text
									class="time__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}&nbsp;时</text>
								<text class="time__item">{{ timeData.minutes }}&nbsp;分</text>
								<text class="time__item">{{ timeData.seconds }}&nbsp;秒</text>
								<text class="time__item">结束</text>
							</view>
						</up-count-down>
					</view>
				</view>

			</view>
			<view class="hulu-empty-paragraph"></view>
			<view class="gui-padding gui-flex gui-space-between gui-align-items-center" style="height:156rpx;">

				<view class="">
					<view class="gui-flex gui-justify-content-start gui-align-items-center">
						<u-icon name="bookmark-fill" color="#2979ff" size="32"></u-icon>
						<text class="gui-h6 gui-boldder">{{groupactivity.title}}</text>
					</view>
					<view class="">
						<view class="gui-text-small gui-color-gray">开抢时间:{{groupactivity.start_time}}</view>
						<view class="gui-text-small gui-color-gray">
							{{groupactivity.Groupcourse?groupactivity.Groupcourse.course_type.name:''}}</view>
					</view>
				</view>
				<view class="gui-flex">
					<view class="gui-color-red1 gui-h3" style="height:156rpx;line-height: 156rpx;">
						<text class="gui-h4">￥</text>
						<text class="gui-h4">{{payAmount}}</text>
						<text class="gui-h4">元</text>
					</view>
					<view class="gui-color-gray-light gui-h3" style="height:156rpx;line-height: 156rpx;">
						<text class="gui-text">￥</text>
						<text class="gui-text gui-line-through">{{groupactivity.price}}</text>
						<text class="gui-text">元</text>
					</view>
				</view>
				
			</view>
			<view class="hulu-empty-paragraph"></view>
			<view class="gui-padding" v-if="canOrder">
				<view class="gui-flex gui-justify-content-start gui-align-items-center">
					<u-icon name="tags-fill" color="#2979ff" size="32"></u-icon>
					<text class="gui-h6 gui-boldder">抢购规则</text>
				</view>
				<view style="" class="gui-bg-white gui-dark-bg-level-3 gui-padding-small gui-margin-top">
					<view
						class="gui-flex gui-rows gui-nowrap gui-border-l gui-border-t gui-bg-gray gui-dark-bg-level-2">
						<text class="gui-td gui-border-r gui-border-b gui-primary-text gui-text-center">人数（大于）</text>
						<text class="gui-td gui-border-r gui-border-b gui-primary-text gui-text-center">抢购价</text>
					</view>	
					<view class="gui-flex gui-rows gui-nowrap gui-border-l" v-for="(item, index) in groupactivity.Groupactivityoptions"
						:key="index">
						<text
							class="gui-td gui-primary-text gui-text-center gui-border-r gui-border-b">{{item.number}}</text>
						<text
							class="gui-td gui-primary-text gui-text-center gui-border-r gui-border-b">{{item.current_price}}元</text>
					</view>
				</view>
			</view>
			<view class="hulu-empty-paragraph"></view>

			<view class="gui-padding">
				<view class="gui-flex gui-justify-content-start gui-align-items-center">
					<u-icon name="tags-fill" color="#2979ff" size="32"></u-icon>
					<text class="gui-h6 gui-boldder">活动说明</text>
				</view>
				<view class="gui-flex">
					<text class="gui-text-small gui-color-gray">规则一:</text>
					<text class="gui-text-small gui-color-gray">获取课程后，请按时参加，过期作废</text>
				</view>
				<view class="gui-flex">
					<text class="gui-text-small gui-color-gray">规则二:</text>
					<text class="gui-text-small gui-color-gray">活动课程不能转增或转售</text>
				</view>
				<view class="gui-flex">
					<text class="gui-text-small gui-color-gray">规则二:</text>
					<text class="gui-text-small gui-color-gray">活动最终解释权归本店所有，如有疑问，请联系本店，谢谢支持</text>
				</view>
			</view>
			<view class="" style="height: 180rpx;">

			</view>
		</view>
		<view class="pay-btn">
			<view class="pay-btn-warp">
				<up-button @tap="callPay" v-if="canOrder" size="large" type="primary"
					color="linear-gradient(45deg,#52e5e7,#130cb7)" shape="circle" text="下单开抢">
				</up-button>
				<up-button v-if="toStartTime>0" size="large" type="primary"
					color="linear-gradient(45deg,#1f1c2c,#928dab)" shape="circle" text="敬请期待">
				</up-button>
				<up-button v-if="remainTime<0" size="large" type="primary"
					color="linear-gradient(45deg,#1f1c2c,#928dab)" shape="circle" text="已结束">
				</up-button>

				<up-button v-if="groupactivity.require_number<=groupactivity.current_number" size="large" type="primary"
					color="linear-gradient(45deg,#1f1c2c,#928dab)" shape="circle" text="已满员">
				</up-button>
			</view>
		</view>
	</view>
</template>
<script setup lang="ts">
	import { onMounted, onUnmounted, ref } from 'vue'
	import useGroupactivity from '@/api/groupactivity'
	import request from '@/utils/request'
	import dayjs from 'dayjs'

	const {
		showGroupactivity,
		groupactivity,
		payAmount
	} = useGroupactivity()
	const remainTime = ref()
	const toStartTime = ref()
	const canOrder = ref(false)
	const timer = ref(null)
	onMounted(async () => {
		await showGroupactivity().then(_ => {
			remainTime.value = dayjs(groupactivity.value.end_time).diff(new Date())
			toStartTime.value = dayjs(groupactivity.value.start_time).diff(new Date())
			//如果当前时间在开始时间和结束时间之内，可以下单
			if (dayjs(groupactivity.value.end_time).diff(new Date()) > 0 && dayjs(groupactivity.value.start_time).diff(new Date()) < 0) {
				canOrder.value = true
			}
			if(groupactivity.value.require_number<=groupactivity.value.current_number){
				canOrder.value=false
			}
		})
		loopGetAct()
	})

	const handleActi = async () => {
		await showGroupactivity().then(_ => {
			remainTime.value = dayjs(groupactivity.value.end_time).diff(new Date())
			toStartTime.value = dayjs(groupactivity.value.start_time).diff(new Date())
			//如果当前时间在开始时间和结束时间之内，可以下单
			if (dayjs(groupactivity.value.end_time).diff(new Date()) > 0 && dayjs(groupactivity.value.start_time).diff(new Date()) < 0) {
				canOrder.value = true
			}
			if(groupactivity.value.require_number<=groupactivity.value.current_number){
				canOrder.value=false
			}
		})
	}
	const loopGetAct = () => {
		// 每隔5s发送一次请求，获得最新的数据
		if (timer.value != null) {
			clearInterval(timer.value)
			timer.value = null
		} else {
			timer.value = setInterval(() => {
				handleActi()
			}, 3000)
		}
	}
	// 使用 reactive 创建响应式对象  
	const timeData = ref({});

	//当程序卸载的时候，取消定时器，清理timer
	const countDownRef = ref()
	onUnmounted(() => {
		if (countDownRef.value) {
			countDownRef.value.reset();
		}
		clearInterval(timer.value)
		timer.value = null
	})


	// 定义 onChange 方法  
	const onChange = (e) => {
		timeData.value = e;
	};

	// 支付价格:
	const callPay = async () => {
		uni.showLoading({
			title: "支付中..."
		})
		const order = await request.post(`mini/grouporder`, {
			groupactive_id: groupactivity.value.ID,
			price: payAmount.value,
			payment_type: "wechat"
		});
		//发送支付请求（获取支付订单号）
		const orderInfo = await request.post(`mini/grouppay/${order.ID}`, order);

		//拉起小程序支付
		if (!orderInfo) {
			return uni.showToast({
				icon: 'error',
				content: '支付失败'
			});
		}
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: orderInfo['timeStamp'],
			nonceStr: orderInfo['nonceStr'],
			package: orderInfo['package'],
			signType: orderInfo['signType'],
			paySign: orderInfo['paySign'],
			success: (res) => {
				uni.hideLoading()
				uni.showToast({
					icon: "success",
					title: "支付成功"
				})
				setTimeout(() => {
					uni.switchTab({
						url: "/pages/index/index"
					})
				}, 1000)
			},
			fail: (err) => {
				uni.hideLoading()
				console.log('fail:' + JSON.stringify(err));
			},
			complete() {
				uni.hideLoading()
			}
		})
	}
</script>
<style scoped lang="scss">
	.custom-style {
		color: white;
		background-color: red;
	}

	.pay-btn {
		height: 180rpx;
		line-height: 180rpx;
		background-color: white;
		position: fixed;
		bottom: 0;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		-webkit-box-shadow: 0px -2px 12px 0px rgba(0, 0, 0, 0.2);
		-moz-box-shadow: 0px -2px 12px 0px rgba(0, 0, 0, 0.2);
		box-shadow: 0px -2px 12px 0px rgba(0, 0, 0, 0.2);

		.pay-btn-warp {
			padding: 0 30rpx;
			width: 700rpx;
		}
	}

	.time {
		@include flex;
		align-items: center;

		&__item {
			color: #fff;
			font-size: 14px;
			text-align: center;
		}
	}
	.gui-td{width:100rpx; flex:1; overflow:hidden; padding:20rpx 10rpx; display:flexbox;}
	.gui-primary-text{line-height:60rpx !important; font-size:24rpx;}
</style>